package com.battle.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.dto.role.UserRoleDto;
import com.battle.pojo.entity.*;
import com.battle.pojo.enums.CaseStatusEnum;
import com.battle.pojo.enums.CaseTypeEnum;
import com.battle.pojo.enums.OrganizationTypeEnum;
import com.battle.pojo.param.caseAlarmPanel.CreateCaseAlarmPanelParam;
import com.battle.pojo.param.caseBaseInfo.*;
import com.battle.pojo.param.casePatrolStation.CreateCasePatrolStationParam;
import com.battle.pojo.param.userMessage.CreateUserMessageParam;
import com.battle.pojo.vo.CityVo;
import com.battle.pojo.vo.caseBaseInfo.*;
import com.battle.pojo.dto.caseBaseInfo.*;
import com.battle.pojo.vo.dataLabelingTask.GetDataLabelingTaskDownListVo;
import com.battle.pojo.vo.label.GetLabelVo;
import com.battle.pojo.vo.user.GetUserListVo;
import com.battle.service.repository.in.*;
import com.battle.service.service.in.*;
import com.battle.service.utils.CityUtil;
import lombok.AllArgsConstructor;
import nirvana.core.context.WebContext;
import nirvana.core.domains.vo.ApiResult;
import nirvana.core.domains.vo.PageResult;
import nirvana.core.exceptions.BizException;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：战例服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 */
@Service
public class CaseBaseInfoServiceImpl implements CaseBaseInfoService {
    @Value("${yitihua.push.url}")
    String pushUrl;

    @Value("${yitihua.push.appId}")
    String appId;

    @Value("${yitihua.push.appKey}")
    String appKey;

    private final CaseBaseInfoRepository caseBaseInfoRepository;
    private final SirensRepository sirensRepository;
    private final CasePatrolStationService patrolStationService;
    private final CaseAlarmPanelService alarmPanelService;
    private final UserRepository userRepository;
    private final OrganizationRepository organizationRepository;
    private final LabelMpRepository labelMpRepository;
    private final UserMessageService userMessageService;
    private final UserOrganizationMpService userOrganizationMpService;
    private final UserAttentionRepository userAttentionRepository;
    private final UserOrganizationMpRepository userOrganizationMpRepository;

    public CaseBaseInfoServiceImpl(CaseBaseInfoRepository caseBaseInfoRepository, SirensRepository sirensRepository, CasePatrolStationService patrolStationService, CaseAlarmPanelService alarmPanelService, UserRepository userRepository, OrganizationRepository organizationRepository, LabelMpRepository labelMpRepository, UserMessageService userMessageService, UserOrganizationMpService userOrganizationMpService, UserAttentionRepository userAttentionRepository, UserOrganizationMpRepository userOrganizationMpRepository) {
        this.caseBaseInfoRepository = caseBaseInfoRepository;
        this.sirensRepository = sirensRepository;
        this.patrolStationService = patrolStationService;
        this.alarmPanelService = alarmPanelService;
        this.userRepository = userRepository;
        this.organizationRepository = organizationRepository;
        this.labelMpRepository = labelMpRepository;
        this.userMessageService = userMessageService;
        this.userOrganizationMpService = userOrganizationMpService;
        this.userAttentionRepository = userAttentionRepository;
        this.userOrganizationMpRepository = userOrganizationMpRepository;
    }


    /**
     * 创建战例
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CreateCaseBaseInfoVo createCaseBaseInfo(CreateCaseBaseInfoParam param) {
        CaseBaseInfo caseBaseInfo = new CaseBaseInfo();
        BeanUtils.copyProperties(param, caseBaseInfo);
        Long id = IdGenerator.SNOW.generate();
        caseBaseInfo.setId(id);

        //如果没有警情mp的话就创建一下mp
        Sirens sirens = sirensRepository.getSirensByApiId(param.getSirensApiId());
        if (sirens == null) {
            sirens = new Sirens();
            sirens.setSirensApiId(param.getSirensApiId());
            sirens.setId(IdGenerator.SNOW.generate());
            sirensRepository.save(sirens);
        }

        //地址默认是浙江省杭州市
        caseBaseInfo.setCity("浙江省杭州市");
        caseBaseInfo.setIsImport(false);
        caseBaseInfo.setStatus(CaseStatusEnum.waitSubmit);

        Integer i = judgmentType(caseBaseInfo.getType(), caseBaseInfo.getOrganizationType());
        if (i == 1 || i == 2) {
            if (i == 1) {
                sirens.setDetachmentPatrolStation(caseBaseInfo.getId());
            } else {
                sirens.setBattalionPatrolStation(caseBaseInfo.getId());
            }
            //战巡处-支队
            CreateCasePatrolStationParam detailsParam = new CreateCasePatrolStationParam();
            detailsParam.setCaseId(id);
            detailsParam.setSirensId(caseBaseInfo.getSirensId());
            patrolStationService.createCasePatrolStation(detailsParam);

            //caseBaseInfo.setName(detailsParam.getName());
        } else if (i == 3) {
            //接处警
            CreateCaseAlarmPanelParam detailsParam = new CreateCaseAlarmPanelParam();
            detailsParam.setCaseId(id);
            detailsParam.setSirensId(caseBaseInfo.getSirensId());
            alarmPanelService.createCaseAlarmPanel(detailsParam);

            sirens.setAlarmPanelId(caseBaseInfo.getId());
            //caseBaseInfo.setName(detailsParam.getName());
        }

        caseBaseInfo.setSirensId(sirens.getId());
        caseBaseInfoRepository.create(caseBaseInfo);
        sirensRepository.updateById(sirens);

        CreateCaseBaseInfoVo vo=new CreateCaseBaseInfoVo();
        vo.setId(caseBaseInfo.getId());
        vo.setName(caseBaseInfo.getName());
        return vo;
    }

    /**
     * 上传战例
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long importCaseBaseInfo(ImportCaseBaseInfoParam param) {
        CaseBaseInfo caseBaseInfo = new CaseBaseInfo();

        //校验警情是否已经被绑定
        Sirens checkSirens = sirensRepository.getSirensByApiId(param.getSirensApiId());
        if (checkSirens != null && checkSirens.getDetachmentPatrolStation() != null && checkSirens.getDetachmentPatrolStation() != 0l) {
            throw new BizException("该警情已通过系统生成了支队级别的战评，不可重复生成");
        }

        BeanUtils.copyProperties(param, caseBaseInfo);
        Long id = IdGenerator.SNOW.generate();
        caseBaseInfo.setId(id);
        caseBaseInfo.setIsImport(true);
        caseBaseInfo.setStatus(CaseStatusEnum.issue);
        caseBaseInfo.setOrganizationType(OrganizationTypeEnum.detachment);
        caseBaseInfo.setType(CaseTypeEnum.patrolStation);

        //上传的战例不需要提交，审批，直接发布
        caseBaseInfo.setIssueUserId(WebContext.getCurrentUserId());
        caseBaseInfo.setIssueDate(LocalDateTime.now());

        caseBaseInfo.setSubmitUserId(WebContext.getCurrentUserId());
        caseBaseInfo.setSubmitDate(LocalDateTime.now());

        caseBaseInfo.setApprovalUserId(WebContext.getCurrentUserId());
        caseBaseInfo.setApprovalDate(LocalDateTime.now());

        if (param.getSirensApiId() != null) {
            //如果没有警情mp的话就创建一下mp
            Sirens sirens = sirensRepository.getSirensByApiId(param.getSirensApiId());
            if (sirens == null) {
                sirens = new Sirens();
                sirens.setSirensApiId(param.getSirensApiId());
                sirens.setId(IdGenerator.SNOW.generate());
                sirensRepository.save(sirens);
            }
            if (sirens.getDetachmentPatrolStation() != null && sirens.getDetachmentPatrolStation() != 0l) {
                throw new BizException("该警情已通过系统生成了支队级别的战评，不可重复生成");
            }
            sirens.setDetachmentPatrolStation(caseBaseInfo.getId());

            sirensRepository.updateById(sirens);
            caseBaseInfo.setSirensId(sirens.getId());
        }

        caseBaseInfoRepository.create(caseBaseInfo);
        return id;
    }

    /**
     * 判断类型
     *
     * @param type
     * @param organizationType
     * @return 1：战巡处-支队
     * 2：战巡处-大队
     * 3：接警处
     */
    Integer judgmentType(CaseTypeEnum type, OrganizationTypeEnum organizationType) {
        //根据类型的不同创建不同的战例详情
        if (type.getId() == CaseTypeEnum.patrolStation.getId()) {
            if (organizationType.getId() == OrganizationTypeEnum.detachment.getId()) {
                return 1;
            } else {
                return 2;
            }
        } else {
            return 3;
        }
    }

    /**
     * 修改战例
     *
     * @param param
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long editCaseBaseInfo(EditCaseBaseInfoParam param) {
        Long id = param.getId();
        CaseBaseInfo caseBaseInfo = caseBaseInfoRepository.getByIdCheck(id);
        BeanUtils.copyProperties(param, caseBaseInfo);

        if (caseBaseInfo.getStatus().getId() != CaseStatusEnum.waitSubmit.getId() && caseBaseInfo.getStatus().getId() != CaseStatusEnum.reject.getId()) {
            throw new BizException("只有待提交和已驳回才能编辑战例");
        }

        if (param.getIsSubmit() != null && param.getIsSubmit()) {
            caseBaseInfo.setStatus(CaseStatusEnum.waitApprove);
            caseBaseInfo.setSubmitDate(LocalDateTime.now());
            caseBaseInfo.setSubmitUserId(WebContext.getCurrentUserId());

            User user = userRepository.getByIdCheck(WebContext.getCurrentUserId());

            String organizationName = userOrganizationMpService.getOrganizationListByUserId(user.getId())
                    .stream()
                    .map(Organization::getName)
                    .collect(Collectors.joining("|"));


            //发送消息
            String type = "提交战例";
            String message = organizationName + "的人员为：" + user.getName() + "提交了战评《：" + caseBaseInfo.getName() + "》的战例，请及时审批";
            CreateUserMessageParam messageParam = new CreateUserMessageParam();
            messageParam.setMessage(message);
            messageParam.setType(type);
            messageParam.setIsRead(false);
            messageParam.setUserId(1838408287823912960L);
            userMessageService.createUserMessage(messageParam);
            // 向一体化发送消息

            String content = "战评《" + caseBaseInfo.getName() + "》的战例，请及时审批";

            sendMessageToYth(param.getId(), content, organizationName, user.getName(), "GE_483f4fe56fab44fba35cc7343aedad64");
        }

        Integer i = judgmentType(caseBaseInfo.getType(), caseBaseInfo.getOrganizationType());
        if (i == 1 || i == 2) {
            //战巡处-支队
            param.getPatrolStation().setCaseId(caseBaseInfo.getId());
            param.getPatrolStation().setSirensId(caseBaseInfo.getSirensId());
            patrolStationService.editCasePatrolStation(param.getPatrolStation());
            caseBaseInfo.setName(param.getPatrolStation().getName());
        } else if (i == 3) {
            //接处警
            param.getAlarmPanel().setCaseId(caseBaseInfo.getId());
            param.getAlarmPanel().setSirensId(caseBaseInfo.getSirensId());
            alarmPanelService.editCaseAlarmPanel(param.getAlarmPanel());
            caseBaseInfo.setName(param.getAlarmPanel().getName());
        }

        caseBaseInfoRepository.edit(caseBaseInfo);
        return id;
    }

    private void sendMessageToYth(Long id, String content, String department, String userName, String receiverEmployeeCode) {
        HttpRequest request = HttpUtil.createPost(pushUrl + "/third/center/createBacklog");
        request.header("appId", appId);
        request.header("appKey", appKey);

        cn.hutool.json.JSONObject requestBody = new cn.hutool.json.JSONObject();
        requestBody.set("content", content);
        requestBody.set("department", department);
        requestBody.set("userName", userName);

        requestBody.set("receiverEmployeeCode", receiverEmployeeCode);
        requestBody.set("redirectUrl", "http://116.198.224.247:40031/#/battles/details?id=" + id);
        request.body(requestBody.toString());
        try (HttpResponse response = request.execute()) {
            if (response.getStatus() != 200) {
                throw new BizException("发送消息失败，状态码：" + response.getStatus());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 撤回战例
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void revocationCase(Long id) {
        CaseBaseInfo caseBaseInfo = caseBaseInfoRepository.getByIdCheck(id);
        CaseStatusEnum status = caseBaseInfo.getStatus();
        //在待审核的状态下撤回，状态为：待提交
        if (caseBaseInfo.getStatus().getId() == CaseStatusEnum.waitApprove.getId()) {
            status = CaseStatusEnum.waitSubmit;
            caseBaseInfo.setSubmitDate(null);
            caseBaseInfo.setSubmitUserId(null);
        }
        //发布后，在24h内可撤回，通过审核发布后的再撤回的状态为：待审核
        else if (caseBaseInfo.getStatus().getId() == CaseStatusEnum.issue.getId()) {
            //判断是否超过24个小时
            LocalDateTime localDateTime = caseBaseInfo.getSubmitDate().plusHours(24);
            if (localDateTime.isBefore(LocalDateTime.now())) {
                throw new BizException("发布超过了24小时，不可以撤回");
            }
            status = CaseStatusEnum.waitApprove;
            caseBaseInfo.setApprovalDate(null);
            caseBaseInfo.setApprovalRemark(null);
            caseBaseInfo.setApprovalUserId(null);
            caseBaseInfo.setIssueUserId(null);
            caseBaseInfo.setIssueDate(null);
        } else {
            throw new BizException("只有待审批和审批发布后24h内才可以撤回");
        }
        caseBaseInfo.setStatus(status);
        caseBaseInfoRepository.updateById(caseBaseInfo);

        //发送消息
        String type = "提交战例";
        String message = "《：" + caseBaseInfo.getName() + "》的战例被撤回";
        CreateUserMessageParam messageParam = new CreateUserMessageParam();
        messageParam.setMessage(message);
        messageParam.setType(type);
        messageParam.setIsRead(false);
        messageParam.setUserId(1838408287823912960L);
        userMessageService.createUserMessage(messageParam);
    }

    /**
     * 审批战例
     *
     * @param param
     */
    @Override
    public void approveCase(ApproveCaseParam param) {
        CaseBaseInfo caseBaseInfo = caseBaseInfoRepository.getByIdCheck(param.getId());
        if (caseBaseInfo.getStatus().getId() != CaseStatusEnum.waitApprove.getId()) {
            throw new BizException("只有待审批的战例才能审批");
        }
        caseBaseInfo.setApprovalRemark(param.getRemark());
        caseBaseInfo.setApprovalUserId(WebContext.getCurrentUserId());
        caseBaseInfo.setApprovalDate(LocalDateTime.now());
        if (param.getIsPass()) {
            caseBaseInfo.setStatus(CaseStatusEnum.issue);
            //审批通过之后自动发布 审批人就是发布人
            caseBaseInfo.setIssueDate(LocalDateTime.now());
            caseBaseInfo.setIssueUserId(WebContext.getCurrentUserId());
        } else {
            caseBaseInfo.setStatus(CaseStatusEnum.reject);
        }
        caseBaseInfoRepository.updateById(caseBaseInfo);
    }

    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.of(2024, 9, 2, 15, 00, 00, 00);
        LocalDateTime time = localDateTime.plusHours(24);
        if (time.isBefore(LocalDateTime.now())) {
            System.out.println("超过了24小时，不可以撤回");
        } else {
            System.out.println("没有超过了24小时，可以撤回");
        }
    }

    /**
     * 移除战例
     *
     * @param id
     */
    @Override
    public void removeCaseBaseInfo(Long id) {
        CaseBaseInfo caseBaseInfo = caseBaseInfoRepository.getByIdCheck(id);
        if (caseBaseInfo.getStatus().getId() != CaseStatusEnum.soldOut.getId()) {
            throw new BizException("只有已下架的战例才能移除");
        }
        caseBaseInfoRepository.removeById(id);

        if (caseBaseInfo.getSirensId()!=null){
            Sirens sirens = sirensRepository.getByIdCheck(caseBaseInfo.getSirensId());

            Integer i = judgmentType(caseBaseInfo.getType(), caseBaseInfo.getOrganizationType());
            if (i == 1) {
                //战巡处-支队
//            patrolStationService.removeCasePatrolStation(id);
                sirens.setDetachmentPatrolStation(null);
            } else if (i == 2) {
                sirens.setBattalionPatrolStation(null);
            } else if (i == 3) {
                //接处警
//            alarmPanelService.removeCaseAlarmPanel(id);
                sirens.setAlarmPanelId(null);
            }
            sirensRepository.updateById(sirens);
        }

    }

    /**
     * 启动/禁用战例
     *
     * @param id
     */
    @Override
    public void enabledCaseBaseInfo(Long id) {
        CaseBaseInfo caseBaseInfo = caseBaseInfoRepository.getByIdCheck(id);
        caseBaseInfo.setIsDisable(!caseBaseInfo.getIsDisable());
        caseBaseInfoRepository.edit(caseBaseInfo);
    }

    /**
     * 获取战例详情
     *
     * @param id
     * @return
     */
    @Override
    public GetCaseBaseInfoVo getCaseBaseInfo(Long id) {
        CaseBaseInfo caseBaseInfo = caseBaseInfoRepository.getByIdCheck(id);
        GetCaseBaseInfoVo vo = new GetCaseBaseInfoVo();
        BeanUtils.copyProperties(caseBaseInfo, vo);

        Integer i = judgmentType(caseBaseInfo.getType(), caseBaseInfo.getOrganizationType());
        if (i == 1 || i == 2) {
            //战巡处-支队
            vo.setPatrolStation(patrolStationService.getCasePatrolStation(id));
        } else if (i == 3) {
            //接处警
            vo.setAlarmPanel(alarmPanelService.getCaseAlarmPanel(id));
        }
        return vo;
    }

    /**
     * 获取战例 列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetCaseBaseInfoListVo> getCaseBaseInfoList(GetCaseBaseInfoListParam param) {

        SelectCaseBaseInfoDto dto = new SelectCaseBaseInfoDto();
        BeanUtils.copyProperties(param, dto);
        dto.setUserId(WebContext.getCurrentUserId());
        Page<CaseBaseInfo> page = caseBaseInfoRepository.selectCaseBaseInfo(dto);
        List<CaseBaseInfo> caseBaseInfoList = page.getRecords();
        List<GetCaseBaseInfoListVo> list = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(caseBaseInfoList)) {
            List<Long> userIds = new ArrayList<>();

            caseBaseInfoList.forEach(v -> {
                userIds.add(v.getIssueUserId());
                userIds.add(v.getSubmitUserId());
                userIds.add(v.getApprovalUserId());
                userIds.add(v.getCreator());
            });
            Map<Long, User> userMap = userRepository.getMap(userIds);

            List<UserOrganizationMp> deptIds = userOrganizationMpRepository.list(
                    new LambdaQueryWrapper<UserOrganizationMp>()
                            .in(
                                    UserOrganizationMp::getUserId,
                                    userIds
                            )
            );
            Map<UserOrganizationMp, Organization> deptMap = organizationRepository.getUserOrganizationMap(deptIds);

            List<Long> attentionIdList = userAttentionRepository.list(
                    new LambdaQueryWrapper<UserAttention>()
                            .eq(UserAttention::getUserId, WebContext.getCurrentUserId())
                            .eq(UserAttention::getIsDelete, false)
                            .in(UserAttention::getFid, caseBaseInfoList.stream().map(CaseBaseInfo::getId).toList())
            ).stream().map(UserAttention::getFid).toList();

            List<Long> ids = caseBaseInfoList.stream().map(CaseBaseInfo::getId).toList();

            Map<Long, List<GetLabelVo>> listMap = labelMpRepository.getListByFidIds(ids);

            for (CaseBaseInfo caseBaseInfo : caseBaseInfoList) {
                GetCaseBaseInfoListVo vo = new GetCaseBaseInfoListVo();
                BeanUtils.copyProperties(caseBaseInfo, vo);
                User operation = userMap.get(caseBaseInfo.getIssueUserId());
                if (operation != null) {
                    vo.setIssueName(operation.getName());
                }
                User submit = userMap.get(caseBaseInfo.getSubmitUserId());
                if (submit != null) {
                    vo.setSubmitUserName(submit.getName());
                }
                User approve = userMap.get(caseBaseInfo.getApprovalUserId());
                if (approve != null) {
                    vo.setApprovalUserName(approve.getName());
                }
                User creator = userMap.get(caseBaseInfo.getCreator());
                UserOrganizationMp creatorOrganization = deptMap.keySet().stream()
                        .filter(organization -> organization.getUserId().equals(caseBaseInfo.getCreator()))
                        .findFirst()
                        .orElse(null);
                if (creator != null) {
                    vo.setCreateUserName(creator.getName());
                    //查询组织架构名称
                    vo.setCreateOrganizationName(
                            deptMap.get(creatorOrganization).getName()
                    );
                    vo.setCreateTime(caseBaseInfo.getCreateTime());
                }

                List<GetLabelVo> roleDtoList = listMap.get(caseBaseInfo.getId());
                if (roleDtoList != null) {
                    String labelName = roleDtoList.stream()
                            .map(GetLabelVo::getName)
                            .collect(Collectors.joining(","));
                    vo.setLabelName(labelName);
                }
                vo.setIsAttention(attentionIdList.contains(caseBaseInfo.getId()));
                if (dto.getIsDeleted() != null) vo.setResourceAddress("战例中心/战例管理");
                list.add(vo);
            }
        }

        return new PageResult<>(list, page);

    }

    /**
     * 恢复战例
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCaseDeleted(Long id) {
        CaseBaseInfo  caseBaseInfo = caseBaseInfoRepository.getByIdDeleted(id);
        if (caseBaseInfo == null) {
            throw new BizException("战例不存在");
        }
        caseBaseInfo.setIsDelete(false);
        caseBaseInfoRepository.updateById(caseBaseInfo);

        if (caseBaseInfo.getSirensId()!=null){
            Sirens sirens = sirensRepository.getByIdCheck(caseBaseInfo.getSirensId());

            Integer i = judgmentType(caseBaseInfo.getType(), caseBaseInfo.getOrganizationType());
            if (i == 1) {
                sirens.setDetachmentPatrolStation(id);
            } else if (i == 2) {
                sirens.setBattalionPatrolStation(id);
            } else if (i == 3) {
                sirens.setAlarmPanelId(id);
            }
            sirensRepository.updateById(sirens);
        }

    }

    @Override
    public List<CaseHomePageVo> selectRecommendCaseList() {
        List<CaseHomePageVo> caseHomePageVos = caseBaseInfoRepository.selectRecommendCaseList();
        if (CollectionUtil.isNotEmpty(caseHomePageVos)){
            for (CaseHomePageVo caseHomePageVo : caseHomePageVos) {
                List<Organization> mpList = userOrganizationMpService.getOrganizationListByUserId(caseHomePageVo.getUserId());
                if (CollectionUtil.isNotEmpty(mpList)){
                    caseHomePageVo.setOrganizationName(mpList.stream().map(Organization::getName).collect(Collectors.joining(",")));
                }
            }
        }
        return caseHomePageVos;
    }

    @Override
    public List<CaseHomePageVo> selectBacklogCaseList() {
        List<CaseHomePageVo> caseHomePageVos = caseBaseInfoRepository.selectBacklogCaseList();
        if (CollectionUtil.isNotEmpty(caseHomePageVos)){
            for (CaseHomePageVo caseHomePageVo : caseHomePageVos) {
                List<Organization> mpList = userOrganizationMpService.getOrganizationListByUserId(caseHomePageVo.getUserId());
                if (CollectionUtil.isNotEmpty(mpList)){
                    caseHomePageVo.setOrganizationName(mpList.stream().map(Organization::getName).collect(Collectors.joining(",")));
                }
            }
        }
        return caseHomePageVos;
    }

    /**
     * 获取战例统计信息
     *
     * @return
     */
    @Override
    public GetCaseBaseInfoQueryVo selectCaseBaseInfo(Integer type) {

        GetCaseBaseInfoQueryVo vo = new GetCaseBaseInfoQueryVo();
        vo.setAllCount(0);
        vo.setFireRescueCount(0);
        vo.setDisasterRescueCount(0);
        vo.setSocialRescueCount(0);
        vo.setAntiTerrorismCount(0);
        vo.setDutyCount(0);

        List<Integer> status=new ArrayList<>();
        status.add(CaseStatusEnum.issue.getId());

        List<CaseBaseInfo> caseBaseInfos = caseBaseInfoRepository.getBaseMapper().selectList(
                new LambdaQueryWrapper<CaseBaseInfo>()
                        .eq(CaseBaseInfo::getIsDelete, false)
                        .in(CaseBaseInfo::getStatus,status)
                        .eq(CaseBaseInfo::getType,type)
        );
        if (CollectionUtil.isNotEmpty(caseBaseInfos)) {
            vo.setAllCount(caseBaseInfos.size());

            //过滤出caseType！=null得
            caseBaseInfos = caseBaseInfos.stream().filter(v -> v.getCaseType() != null).collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(caseBaseInfos)) {
                //火灾扑救数量
                List<CaseBaseInfo> fireRescue = caseBaseInfos.stream().filter(v -> v.getCaseType().equals("火灾扑救")).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(fireRescue)) {
                    vo.setFireRescueCount(fireRescue.size());
                }

                //获取抢险救援
                List<CaseBaseInfo> disasterRescue = caseBaseInfos.stream().filter(v -> v.getCaseType().equals("抢险救援")).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(disasterRescue)) {
                    vo.setDisasterRescueCount(disasterRescue.size());
                }
                //获取社会救助
                List<CaseBaseInfo> socialAssistance = caseBaseInfos.stream().filter(v -> v.getCaseType().equals("社会救助")).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(socialAssistance)) {
                    vo.setSocialRescueCount(socialAssistance.size());
                }

                //获取反恐排爆
                List<CaseBaseInfo> antiTerrorism = caseBaseInfos.stream().filter(v -> v.getCaseType().equals("反恐排爆")).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(antiTerrorism)) {
                    vo.setAntiTerrorismCount(antiTerrorism.size());
                }

                //公务执勤数量
                List<CaseBaseInfo> duty = caseBaseInfos.stream().filter(v -> v.getCaseType().equals("公务执勤")).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(duty)) {
                    vo.setDutyCount(duty.size());
                } else {
                    vo.setDutyCount(0);
                }
            }

        }


        return vo;
    }

    /**
     * 获取城市下拉框
     * @return
     */
    @Override
    public List<CityVo> getCityList() {
        Map<String, List<String>> vo= CityUtil.getCascadingCities();
        //将vo转换为CityVo
        List<CityVo> cityVoList = new ArrayList<>();
        vo.forEach((k,v)->{
            CityVo cityVo = new CityVo();
            cityVo.setName(k);
            List<CityVo> children = new ArrayList<>();
            v.forEach(c->{
                CityVo cityVo1 = new CityVo();
                cityVo1.setName(c);
                children.add(cityVo1);
            });
            cityVo.setChildren(children);
            cityVoList.add(cityVo);
        });
        return cityVoList;
    }

    @Override
    public List<GetCaseBaseInfoDownListVo> getCaseBaseInfoDownList(GetCaseBaseInfoDownListParam param) {
        CaseBaseInfo po = new CaseBaseInfo();
        if (param != null) {
            BeanUtils.copyProperties(param, po);
        }
        List<CaseBaseInfo> dataLabelingTaskList = caseBaseInfoRepository.getListByEntity(po);

        List<GetCaseBaseInfoDownListVo> list = new ArrayList<>();
        for (CaseBaseInfo dataLabelingTask : dataLabelingTaskList) {
            GetCaseBaseInfoDownListVo vo = new GetCaseBaseInfoDownListVo();
            BeanUtils.copyProperties(dataLabelingTask, vo);
            list.add(vo);
        }
        return list;
    }

    /**
     * 查看审批情况
     * @param id
     * @return
     */
    @Override
    public CaseBaseInfoAuditVo getCaseBaseInfoAudit(Long id) {
        CaseBaseInfo caseBaseInfo = caseBaseInfoRepository.getByIdCheck(id);
        CaseBaseInfoAuditVo vo = new CaseBaseInfoAuditVo();
        BeanUtils.copyProperties(caseBaseInfo, vo);

        JSONArray auditList=new JSONArray();

        //创建人
        User create = userRepository.getById(caseBaseInfo.getCreator());
        if (create != null) {
            JSONObject createJson = new JSONObject();
            createJson.put("label","'创建战例");
            createJson.put("name",create.getName());
            createJson.put("time",caseBaseInfo.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            List<Organization> organizationList = userOrganizationMpService.getOrganizationListByUserId(create.getId());
            if (CollectionUtil.isNotEmpty(organizationList)) {
                createJson.put("department", organizationList.stream().map(Organization::getName).collect(Collectors.joining(",")));
            }
            auditList.add(createJson);
        }

        //提交人
        User submit = userRepository.getById(caseBaseInfo.getSubmitUserId());
        if (submit != null) {
            JSONObject createJson = new JSONObject();
            createJson.put("label","'提交战例");
            createJson.put("name",submit.getName());
            createJson.put("time",caseBaseInfo.getSubmitDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            List<Organization> organizationList = userOrganizationMpService.getOrganizationListByUserId(submit.getId());
            if (CollectionUtil.isNotEmpty(organizationList)) {
                createJson.put("department", organizationList.stream().map(Organization::getName).collect(Collectors.joining(",")));
            }
            auditList.add(createJson);
        }
        //审批人
        User approve = userRepository.getById(caseBaseInfo.getApprovalUserId());
        if (approve != null) {
            JSONObject createJson = new JSONObject();
            createJson.put("label","'审批战例");
            createJson.put("name",approve.getName());
            createJson.put("time",caseBaseInfo.getSubmitDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            List<Organization> organizationList = userOrganizationMpService.getOrganizationListByUserId(approve.getId());
            if (CollectionUtil.isNotEmpty(organizationList)) {
                createJson.put("department", organizationList.stream().map(Organization::getName).collect(Collectors.joining(",")));
            }
            auditList.add(createJson);
        }
        //发布人
        User issue = userRepository.getById(caseBaseInfo.getIssueUserId());
        if (issue != null) {
            JSONObject createJson = new JSONObject();
            createJson.put("label","'发布战例");
            createJson.put("name",issue.getName());
            createJson.put("time",caseBaseInfo.getSubmitDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            List<Organization> organizationList = userOrganizationMpService.getOrganizationListByUserId(issue.getId());
            if (CollectionUtil.isNotEmpty(organizationList)) {
                createJson.put("department", organizationList.stream().map(Organization::getName).collect(Collectors.joining(",")));
            }
            auditList.add(createJson);
        }
        vo.setAuditList(auditList);
        return vo;
    }


}



